package me.zhengjie.modules.security.rest

import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import me.zhengjie.logging.annotation.Log
import me.zhengjie.common.utils.EncryptUtils
import me.zhengjie.modules.security.service.OnlineUserService
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*
import java.io.IOException

@RestController
@RequestMapping("/auth/online")
@Schema(description = "系统：在线用户管理")
class OnlineController(private val onlineUserService: OnlineUserService) {
    @Schema(description = "查询在线用户")
    @GetMapping
    @PreAuthorize("@el.check()")
    fun getAll(username: String?, pageable: Pageable?): ResponseEntity<*> {
        return ResponseEntity(onlineUserService.getAll(username!!, pageable!!), HttpStatus.OK)
    }

    @Log("导出数据")
    @Schema(description = "导出数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check()")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, username: String?) {
        onlineUserService.download(onlineUserService.getAll(username!!), response)
    }

    @Schema(description = "踢出用户")
    @DeleteMapping
    @PreAuthorize("@el.check()")
    @Throws(Exception::class)
    fun deleteOnlineUser(@RequestBody keys: Set<String?>): ResponseEntity<Any?>? {
        for (token in keys) {
            // 解密Key
            var t = EncryptUtils.desDecrypt(token!!)
            onlineUserService.logout(t)
        }
        return ResponseEntity(HttpStatus.OK)
    }
}